<script setup lang="ts">
import { ref } from 'vue';


const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'upload', files: File[], relativePaths: string[]): void;
}>();

const fileInput = ref<HTMLInputElement | null>(null);
const selectedFiles = ref<File[]>([]);
const relativePaths = ref<string[]>([]);
const errorMessage = ref('');

// 支持的文件类型
const supportedTypes = [
  'text/plain', // .txt
  'application/pdf', // .pdf
  'application/msword', // .doc
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
  // 'application/vnd.ms-excel', // .xls
  // 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
  'application/vnd.ms-powerpoint', // .ppt
  'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
  'text/markdown', // .md
  // 'text/csv', // .csv
  'application/json', // .json
];

// 处理文件夹选择
const handleDirectoryChange = async (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (!input.files || input.files.length === 0) {
    selectedFiles.value = [];
    relativePaths.value = [];
    errorMessage.value = '';
    return;
  }

  const files: File[] = [];
  const paths: string[] = [];
  const unsupportedFiles: string[] = [];

  // 处理所有选择的文件
  for (let i = 0; i < input.files.length; i++) {
    const file = input.files[i];
    if (supportedTypes.includes(file.type)) {
      files.push(file);
      // 获取相对路径
      const relativePath = (file as any).webkitRelativePath || file.name;
      paths.push(relativePath);
    } else {
      unsupportedFiles.push(file.name);
    }
  }

  if (unsupportedFiles.length > 0) {
    errorMessage.value = `不支持的文件类型: ${unsupportedFiles.join(', ')}`;
  } else {
    errorMessage.value = '';
  }

  selectedFiles.value = files;
  relativePaths.value = paths;
};

// 处理拖放
const isDragging = ref(false);

const handleDragEnter = (event: DragEvent) => {
  event.preventDefault();
  isDragging.value = true;
};

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault();
  isDragging.value = false;
};

const handleDragOver = (event: DragEvent) => {
  event.preventDefault();
};

const handleDrop = async (event: DragEvent) => {
  event.preventDefault();
  isDragging.value = false;

  if (!event.dataTransfer?.items) return;

  const files: File[] = [];
  const paths: string[] = [];
  const unsupportedFiles: string[] = [];

  // 处理拖放的文件夹
  const processEntry = async (entry: FileSystemEntry, path: string = '') => {
    if (entry.isFile) {
      const fileEntry = entry as FileSystemFileEntry;
      const file = await new Promise<File>((resolve) => {
        fileEntry.file(resolve);
      });

      if (supportedTypes.includes(file.type)) {
        files.push(file);
        paths.push(path + file.name);
      } else {
        unsupportedFiles.push(file.name);
      }
    } else if (entry.isDirectory) {
      const dirEntry = entry as FileSystemDirectoryEntry;
      const dirReader = dirEntry.createReader();
      const entries = await new Promise<FileSystemEntry[]>((resolve) => {
        dirReader.readEntries(resolve);
      });

      for (const childEntry of entries) {
        await processEntry(childEntry, path + entry.name + '/');
      }
    }
  };

  for (const item of event.dataTransfer.items) {
    const entry = item.webkitGetAsEntry();
    if (entry) {
      await processEntry(entry);
    }
  }

  if (unsupportedFiles.length > 0) {
    errorMessage.value = `不支持的文件类型: ${unsupportedFiles.join(', ')}`;
  } else {
    errorMessage.value = '';
  }

  selectedFiles.value = files;
  relativePaths.value = paths;
};

// 处理上传
const uploadProgress = ref<Record<string, number>>({});
const isUploading = ref(false);

const handleUpload = async () => {
  if (selectedFiles.value.length === 0) {
    errorMessage.value = '请选择文件夹';
    return;
  }

  isUploading.value = true;
  uploadProgress.value = {};
  selectedFiles.value.forEach(file => {
    uploadProgress.value[file.name] = 0;
  });

  emit('upload', selectedFiles.value, relativePaths.value);
  setTimeout(() => {
    isUploading.value = false;
    emit('close');
  }, 1000);
};

// 处理取消
const handleCancel = () => {
  selectedFiles.value = [];
  relativePaths.value = [];
  errorMessage.value = '';
  emit('close');
};

// 触发文件夹选择器点击
const triggerDirectoryInput = () => {
  fileInput.value?.click();
};
</script>

<template>
  <div class="modal-overlay">
    <div class="modal-container">
      <div class="modal-header">
        <h3>上传文件夹</h3>
        <button class="close-btn" @click="handleCancel">&times;</button>
      </div>
      
      <div class="modal-body">
        <div
          class="drop-zone"
          :class="{ 'dragging': isDragging }"
          @dragenter="handleDragEnter"
          @dragleave="handleDragLeave"
          @dragover="handleDragOver"
          @drop="handleDrop"
        >
          <input
            ref="fileInput"
            type="file"
            webkitdirectory
            @change="handleDirectoryChange"
            style="display: none"
          />
          <div class="drop-zone-content">
            <p>拖放文件夹到此处或</p>
            <button class="select-directory-btn" @click="triggerDirectoryInput">
              选择文件夹
            </button>
          </div>
        </div>
        
        <div v-if="selectedFiles.length > 0" class="selected-files">
          <h4>已选择 {{ selectedFiles.length }} 个文件</h4>
          <div class="file-list">
            <div v-for="(path, index) in relativePaths" :key="index" class="file-item">
              {{ path }}
            </div>
          </div>
        </div>
        
        <div v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </div>
        
        <div v-if="isUploading" class="upload-progress">
          <div v-for="(progress, fileName) in uploadProgress" :key="fileName" class="progress-item">
            <div class="file-name">{{ fileName }}</div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: `${progress}%` }"></div>
            </div>
            <div class="progress-text">{{ progress }}%</div>
          </div>
        </div>
        
        <div class="supported-types">
          <p>支持的文件类型：</p>
          <ul>
            <li>文本文件 (.txt)</li>
            <li>PDF文件 (.pdf)</li>
            <li>Word文档 (.doc, .docx)</li>
            <!-- <li>Excel表格 (.xls, .xlsx)</li> -->
            <li>PowerPoint演示文稿 (.ppt, .pptx)</li>
            <li>Markdown文件 (.md)</li>
            <!-- <li>CSV文件 (.csv)</li> -->
            <li>JSON文件 (.json)</li>
          </ul>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button 
          class="upload-btn" 
          @click="handleUpload"
          :disabled="selectedFiles.length === 0"
        >
          上传
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-container {
  background-color: white;
  border-radius: 8px;
  width: 600px;
  max-width: 90%;
  max-height: 90vh;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex-grow: 1;
}

.drop-zone {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.drop-zone.dragging {
  border-color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
}

.drop-zone-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.drop-zone-content p {
  margin: 0;
  color: #666;
}

.select-directory-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.selected-files {
  margin: 20px 0;
}

.selected-files h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.file-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
}

.file-item {
  padding: 5px;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-item:not(:last-child) {
  border-bottom: 1px solid #eee;
}

.error-message {
  color: #d9534f;
  margin: 15px 0;
  padding: 10px;
  background-color: #fdf7f7;
  border-radius: 4px;
}

.supported-types {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.supported-types p {
  margin-top: 0;
  font-weight: bold;
  color: #333;
}

.supported-types ul {
  margin: 10px 0 0;
  padding-left: 20px;
  columns: 2;
}

.supported-types li {
  margin-bottom: 5px;
  color: #666;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.upload-btn {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.upload-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.upload-progress {
  margin: 15px 0;
}

.progress-item {
  margin-bottom: 10px;
}

.file-name {
  font-size: 14px;
  margin-bottom: 5px;
  color: #555;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.progress-bar {
  height: 10px;
  background-color: #f0f0f0;
  border-radius: 5px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #4CAF50;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  text-align: right;
  color: #777;
  margin-top: 3px;
}
</style>